﻿using System;
using System.Linq;
using Avalonia;
using Avalonia.Controls;
using DevManager.Services;
using DevManager.StatusBars;
using DevManager.ViewModels.Pages;
using DevManager.Views;
using FluentAvalonia.UI.Controls;

namespace DevManager.Pages;

public partial class EnvPathPage : PageBase
{
    public EnvPathPage()
    {
        InitializeComponent();
        DataContext = new EnvPathPageModel();
    }

    protected override void OnAttachedToVisualTree(VisualTreeAttachmentEventArgs e)
    {
        base.OnAttachedToVisualTree(e);
        var mainView = ViewService.GetView<MainView>(this);
        if (mainView == null) return;
        DataContext = new EnvPathPageModel(mainView.Info);
    }

    public async void Downland(string name)
    {
        if (DataContext is not EnvPathPageModel model) return;
        var language = model.Language.Info.Languages.FirstOrDefault(x => x.Name == name);
        if (language == null) return;

        var td = new TaskDialog
        {
            // Title property only applies on Windowed dialogs
            Title = "FluentAvalonia",
            Header = "Header",
            Content = new DownloadPage(language),
            IconSource = new SymbolIconSource { Symbol = Symbol.Code },
            //FooterVisibility = TaskDialogFooterVisibility.Auto,
            //Footer = new CheckBox { Content = "Never show me this again" },
            Buttons =
            {
                TaskDialogButton.OKButton,
                TaskDialogButton.CloseButton
            },
            XamlRoot = (Visual)VisualRoot!,
        };

        (string url, string path) a = ("","");
        
        td.Closing += (s, e) =>
        {
            // We only want to use the deferral on the 'Yes' Button
            if ((TaskDialogStandardResult)e.Result != TaskDialogStandardResult.OK) return;
            a = (s.Content as DownloadPage)!.GetResult();
        };
        await td.ShowAsync();
        if(string.IsNullOrEmpty(a.url) || string.IsNullOrEmpty(a.path))return;
        var main = ViewService.GetView<MainView>(this);
        main?.Download(a.url,a.path,name);
    }

    public void Package(string name)
    {
        var main = ViewService.GetView<MainView>(this);
        if(main == null)return;
        var c = main.Info.Info.PackageList.FirstOrDefault(x => x.Key == name);
        var view = new PackageListPageModel(c);
        main.Navigate(view);
    }

    private void BoxInitialized(object? sender, EventArgs e)
    {
        if(sender is not FAComboBox box)return;
        box.SelectedIndex = 0;
    }
}